package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishFlavorDto;
import com.sky.dto.DishPageDto;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.SetmealDish;
import com.sky.exception.extend.DeletionNotAllowedException;
import com.sky.exception.extend.SetmealDishNoEmptyException;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.IDishFlavorService;
import com.sky.service.IDishService;
import com.sky.vo.DishItemVo;
import com.sky.vo.DishPageVo;
import com.sky.vo.DishVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
@Transactional
@Slf4j
public class DishServiceImpl implements IDishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private IDishFlavorService dishFlavorService;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Override
    public PageResult<DishPageVo> queryByPage(DishPageDto dishPageDto) {
        PageHelper.startPage(dishPageDto.getPage(),dishPageDto.getPageSize());
        Page<Dish> dishPage=dishMapper.queryByPage(dishPageDto);
        List<DishPageVo> dishPageVoList = dishPage.getResult().stream().map((item) -> {
            DishPageVo dishPageVo = new DishPageVo();
            String categoryName = categoryMapper.getById(item.getCategoryId());
            BeanUtils.copyProperties(item, dishPageVo);
            dishPageVo.setCategoryName(categoryName);
            return dishPageVo;
        }).collect(Collectors.toList());
        return new PageResult<>(dishPage.getTotal(),dishPageVoList);
    }

    @Override
    public void saveDish(DishFlavorDto dishFlavorDto) {
        Dish dish=new Dish();
        BeanUtils.copyProperties(dishFlavorDto,dish);
        dish.setStatus(1);
        dishMapper.insert(dish);
        if(dishFlavorDto.getFlavors()!=null&& !dishFlavorDto.getFlavors().isEmpty()){
            List<DishFlavor> flavors = dishFlavorDto.getFlavors();
            flavors.forEach((item)->{
                item.setDishId(dish.getId());
            });
            //批量插入
            dishFlavorService.insertBatch(flavors);
        }
    }

    @Override
    public List<Dish> listByCategoryId(Long categoryId) {
        return dishMapper.listDishes(categoryId);
    }

    @Override
    public void updateStatus(Dish dish) {
        //先进行检查
        if (dish.getStatus()==0){
            //如果 该状态对应的菜品id有没有关联套餐，如果关联，那么不能停售。
            int num = setmealDishMapper.getCount(dish.getId());
            if(num!=0){
                throw new SetmealDishNoEmptyException(MessageConstant.SETMEAL_DISHES_ARE_EXIST);
            }
        }
        //正常业务
        dishMapper.modifyStatus(dish);
    }

    @Override
    public int countDishes(Long categoryId) {
        return dishMapper.countByCategoryId(categoryId);
    }

    @Override
    public DishVo getById(Long id) {
        //是多表查询
        //
        Dish dish =dishMapper.queryById(id);
        //再根据dish.getCategoryId的得到整个category
        Category category= categoryMapper.getCategory(dish.getCategoryId());
        List<DishFlavor> flavors=dishFlavorService.queryByDishId(dish.getId());
        DishVo dishVo=new DishVo();
        BeanUtils.copyProperties(dish,dishVo);
        dishVo.setCategoryName(category.getName());
        dishVo.setFlavors(flavors);
        return dishVo;
    }

    @Override
    public void modifyDish(DishFlavorDto dishFlavorDto) {
        //新增
        dishMapper.modifyDish(dishFlavorDto);
        //在给菜品口味表给改了
        // 不如先删除
        dishFlavorService.deleteByDishId(dishFlavorDto.getId());
        //再插入
        List<DishFlavor> flavors = dishFlavorDto.getFlavors();
        if(flavors!=null&& !flavors.isEmpty()){
            flavors.forEach((item)->{
                item.setDishId(dishFlavorDto.getId());
            });
            dishFlavorService.insertBatch(flavors);
        }
    }

    @Override
    public void deleteDish(List<Long> ids) {
        ids.forEach((id)->{
            Dish dish = dishMapper.queryById(id);
            if(Objects.equals(dish.getStatus(), StatusConstant.ENABLE)){
                throw new DeletionNotAllowedException(MessageConstant.DELETE_NOT_ALLOWED);
            }
        });
        //查看这些菜品id有没有关联套餐表,如果有，那么抛业务异常
       List<Long> setmealIds= setmealDishMapper.getSetmealIdsByDishIds(ids);
       if(!setmealIds.isEmpty()){
           //说明与菜品与套餐进行了关联，抛业务异常
           throw new DeletionNotAllowedException(MessageConstant.SETMEAL_DISHES_ARE_EXIST);
       }
       //如果都没抛业务异常说明，可以删
        ids.forEach((id)->{
            dishMapper.deleteById(id);
            dishFlavorService.deleteByDishId(id);
        });
    }

    @Override
    public List<DishVo> dishesWithFlavor(Long categoryId) {
        List<Dish> dishes = dishMapper.listDishes(categoryId);
        List<DishVo> dishVos = dishes.stream().map((item) -> {
            DishVo dishVo = new DishVo();
            BeanUtils.copyProperties(item, dishVo);
            List<DishFlavor> dishFlavors = dishFlavorMapper.getByDishId(item.getId());
            dishVo.setFlavors(dishFlavors);
            String categoryName = categoryMapper.getById(item.getCategoryId());
            dishVo.setCategoryName(categoryName);
            return dishVo;
        }).collect(Collectors.toList());
        return dishVos;
    }

    @Override
    public List<DishItemVo> getBySetmealId(Long id) {
        List<SetmealDish> setmealDishes = setmealDishMapper.getSetmealDishesBySetmealId(id);
        return setmealDishes.stream().map((item)->{
            DishItemVo dishItemVo=new DishItemVo();
            BeanUtils.copyProperties(item,dishItemVo);
            Dish dish = dishMapper.queryById(item.getDishId());
            dishItemVo.setDescription(dish.getDescription());
            dishItemVo.setImage(dish.getImage());
           // log.info("{}",dishItemVo.toString()); 测试成功
            return dishItemVo;
        }).collect(Collectors.toList());
    }
}
